package com.warm.androidstudy.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import javax.security.auth.x500.X500Principal;

/**
 * Created by Administrator on 2017/11/16.
 */

public class AppUtils {

    private static final String TAG = "AppUtils";

    private static final X500Principal DEBUG_DN = new X500Principal("CN=Android Debug,O=Android,C=US");

    private AppUtils() {
        throw new Error("Do not need instantiate!");
    }

    public static int getVerCode(Context context) {
        int verCode = -1;

        try {
            String e = context.getPackageName();
            verCode = context.getPackageManager().getPackageInfo(e, 0).versionCode;
        } catch (PackageManager.NameNotFoundException var3) {
            var3.printStackTrace();
        }
        return verCode;
    }

    public static String getVerName(Context context) {
        String verName = "";

        try {
            String e = context.getPackageName();
            verName = context.getPackageManager().getPackageInfo(e, 0).versionName;
        } catch (PackageManager.NameNotFoundException var3) {
            var3.printStackTrace();
        }

        return verName;
    }

    public static String getAppName(Context context) {
        try {
            PackageManager e = context.getPackageManager();
            PackageInfo packageInfo = e.getPackageInfo(context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (PackageManager.NameNotFoundException var4) {
            var4.printStackTrace();
            return null;
        }
    }

    /**
     * 检测本地该包名下的应用是否存在
     * @param context
     * @param packageName
     * @return
     */
    public static boolean checkPackage(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    public static void installApk(Context context, File file) {
        Intent intent = new Intent();
        intent.addFlags(268435456);
        intent.setAction("android.intent.action.VIEW");
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public static void installApk(Context context, Uri file) {
        Intent intent = new Intent();
        intent.addFlags(268435456);
        intent.setAction("android.intent.action.VIEW");
        intent.setDataAndType(file, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public static void uninstallApk(Context context, String packageName) {
        Intent intent = new Intent("android.intent.action.DELETE");
        Uri packageURI = Uri.parse("package:" + packageName);
        intent.setData(packageURI);
        context.startActivity(intent);
    }

    public static boolean stopRunningService(Context context, String className) {
        Intent intent_service = null;
        boolean ret = false;

        try {
            intent_service = new Intent(context, Class.forName(className));
        } catch (Exception var5) {
            var5.printStackTrace();
        }

        if (intent_service != null) {
            ret = context.stopService(intent_service);
        }

        return ret;
    }

    public static int getNumCores() {
        try {
            File e = new File("/sys/devices/system/cpu/");
            File[] files = e.listFiles(new FileFilter() {
                public boolean accept(File pathname) {
                    return Pattern.matches("cpu[0-9]", pathname.getName());
                }
            });
            return files.length;
        } catch (Exception var2) {
            return 1;
        }
    }

    private static String hexdigest(byte[] paramArrayOfByte) {
        char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

        try {
            MessageDigest e = MessageDigest.getInstance("MD5");
            e.update(paramArrayOfByte);
            byte[] arrayOfByte = e.digest();
            char[] arrayOfChar = new char[32];
            int i = 0;

            for (int j = 0; i < 16; ++j) {
                byte k = arrayOfByte[i];
                arrayOfChar[j] = hexDigits[15 & k >>> 4];
                ++j;
                arrayOfChar[j] = hexDigits[k & 15];
                ++i;
            }

            return new String(arrayOfChar);
        } catch (Exception var8) {
            var8.printStackTrace();
            return "";
        }
    }

    public static List<PackageInfo> getAllApps(Context context) {
        ArrayList apps = new ArrayList();
        PackageManager pManager = context.getPackageManager();
        List paklist = pManager.getInstalledPackages(0);

        for (int i = 0; i < paklist.size(); ++i) {
            PackageInfo pak = (PackageInfo) paklist.get(i);
            if ((pak.applicationInfo.flags & 1) <= 0) {
                apps.add(pak);
            }
        }

        return apps;
    }

    public static int getSDKVersion() {
        return Build.VERSION.SDK_INT;
    }

    public static boolean isDalvik() {
        return "Dalvik".equals(getCurrentRuntimeValue());
    }

    public static boolean isART() {
        String currentRuntime = getCurrentRuntimeValue();
        return "ART".equals(currentRuntime) || "ART debug build".equals(currentRuntime);
    }

    public static String getCurrentRuntimeValue() {
        try {
            Class e = Class.forName("android.os.SystemProperties");

            try {
                Method e1 = e.getMethod("get", new Class[]{String.class, String.class});
                if (e1 == null) {
                    return "WTF?!";
                } else {
                    try {
                        String e2 = (String) e1.invoke(e, new Object[]{"persist.sys.dalvik.vm.lib", "Dalvik"});
                        return "libdvm.so".equals(e2) ? "Dalvik" : ("libart.so".equals(e2) ? "ART" : ("libartd.so".equals(e2) ? "ART debug build" : e2));
                    } catch (IllegalAccessException var3) {
                        return "IllegalAccessException";
                    } catch (IllegalArgumentException var4) {
                        return "IllegalArgumentException";
                    } catch (InvocationTargetException var5) {
                        return "InvocationTargetException";
                    }
                }
            } catch (NoSuchMethodException var6) {
                return "SystemProperties.get(String key, String def) method is not found";
            }
        } catch (ClassNotFoundException var7) {
            return "SystemProperties class is not found";
        }
    }

    public static boolean sdcardMounted() {
        return Environment.getExternalStorageState().equals("mounted");
    }

    public static long getSDAvaliableSize() {
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        long blockSize = (long) sf.getBlockSize();
        long availableBlocks = (long) sf.getAvailableBlocks();
        return availableBlocks * blockSize / 1024L / 1024L;
    }

    public static long getSDTotalSize() {
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        long blockSize = (long) sf.getBlockSize();
        long totalBlocks = (long) sf.getBlockCount();
        return totalBlocks * blockSize / 1024L / 1024L;
    }

    public static boolean isFolderExist(String dir) {
        File folder = new File(dir);
        return folder.exists() && folder.isDirectory() || folder.mkdirs();
    }

    public static Point getScreenMetrics(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int w_screen = dm.widthPixels;
        int h_screen = dm.heightPixels;
        return new Point(w_screen, h_screen);
    }

    public static int px2dip(Context context, float pxValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5F);
    }

    public static int dip2px(Context context, float dipValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5F);
    }

    public static int px2sp(Context context, float pxValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5F);
    }

    public static int sp2px(Context context, float spValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5F);
    }

    public static float getScreenRate(Context context) {
        Point P = getScreenMetrics(context);
        float H = (float) P.y;
        float W = (float) P.x;
        return H / W;
    }

    public static void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 获得设备序列号（如：WTK7N16923005607）, 个别设备无法获取
     *
     * @return 设备序列号
     */
    public static String getSERIAL(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        if (context == null) {
            return "";
        }

        String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        return (TextUtils.isEmpty(androidId) ? "" : androidId);


    }

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName=null;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
        } catch (Exception e) {
        }
        return versionName;
    }
}
